package org.yinxue.example.netty.server;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * SimpleExecutor {@link org.yinxue.example.netty.server} <br>
 *
 * @author zengjian
 * @date 2019/7/10 11:07
 * @since 1.0.0
 */
public class SimpleExecutor implements Executor {

    BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
    Thread thread = new Thread(() -> {
        while (true) {
            Runnable task = null;
            try {
                task = queue.take();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (task != null) {
                task.run();
            }
        }
    });

    @Override
    public void execute(Runnable command) {
        queue.offer(command);
        if (!thread.getState().equals(Thread.State.RUNNABLE)) {
            thread.start();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Executor executor = new SimpleExecutor();
        executor.execute(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println(i);
            }
        });
    }
}